import 'package:dio/dio.dart';

import 'config.dart';

class HttpUtils {
  static final BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.timeout);

  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url,
      {String method = "get",
      Map<String, dynamic> params,
      Interceptor interceptor}) async {
    // 创建单独配置
    Options options = Options(method: method);

    // 全局拦截器
    Interceptor dInter = InterceptorsWrapper(onRequest: (options) {
      print('请求拦截：${options.uri}');
      return options;
    }, onResponse: (response) {
      print('响应拦截');
      return response;
    }, onError: (error) {
      print('错误拦截');
      return error;
    });

    List<Interceptor> interceptors = [dInter];
    if (interceptor != null) {
      interceptors.add(interceptor);
    }

    // 添加到dio拦截器中
    dio.interceptors.addAll(interceptors);

    try {
      Response response =
          await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }
}
